// ------------------------------------
// Actions
// ------------------------------------
import { createAction } from 'http-services'
import * as types from './constant'
import { HttpServices, REDUX_FETCH_TIMEOUT } from 'services/utils'
import * as storageService from 'services/storage'
import _ from 'lodash'
import fetchMock from 'fetch-mock'
import { getToken, setToken } from 'services/token'
import qs from 'query-string'

export const getlist = (options = null) => dispatch => {
  dispatch(createAction(types.ADMINSLOG_FETCH_LIST_BEGIN, null))
  setTimeout(() => new Promise(async (resolve, reject) => {
    try {
      const token = getToken()
      const header = {
        Authorization: token
      }
      options = filterOptions(options)
      if (_.has(options, 'user')) {
        options['user'] = _.map(options['user'], 'key')
      }
      const result = await HttpServices.GET(`/admins/logs`, options, header)
      fetchMock.restore()
      dispatch(createAction(types.ADMINSLOG_FETCH_LIST_SUCCESS, result))
      resolve(result)
    } catch (error) {
      dispatch(createAction(types.ADMINSLOG_FETCH_LIST_FAILURE, error))
      reject(error)
    }
  })
  .catch(() => {}), REDUX_FETCH_TIMEOUT)
}

const filterOptions = (options) => {
  if (options) {
    _.unset(options, 'counts')
    _.unset(options, 'page_size')
    options.page === 1 && _.unset(options, 'page')
    if (_.has(options, 'group') && _.isArray(options.group)) {
      options.group = _.join(options.group, '|')
    }
  }
  return options
}